package com.itheima.controller;

import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class UploadController {

    @Value("${reggie.path}")
    private String path;

    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {
        //获得文件名字
        String filename = file.getOriginalFilename();
        filename = filename.substring(filename.indexOf("."));
        //用uuid使文件名不同
        String s = UUID.randomUUID().toString().replace("-","");
        filename = s+filename;

        System.out.println("新文件名字为:"+filename);

        //1.创建一个文件夹.
        File file1 = new File(path);
        if(!file1.exists()){
            //如果文件夹不存在,需要创建一个文件夹存放图片
            file1.mkdirs();//创建文件夹
        }
        //把文件写入到指定的位置
        file.transferTo(new File(path+filename));

        return R.success(filename);
    }

    @GetMapping("/download")
    public void download(String name,HttpServletResponse response) throws IOException {
        //输入流,通过输入流读取文件内容
        FileInputStream fis = new FileInputStream(new File(path + name));
        //输出流,通过输出流将文件写回浏览器
        ServletOutputStream outputStream = response.getOutputStream();
        //返回给前端的是一个图片
        response.setContentType("image/jpeg");

        int len=0;
        byte[] bytes = new byte[1024];
        while ((len=fis.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        //关闭资源
        outputStream.close();
        fis.close();
    }
}
